package org.jeecg.modules.demo.basestaffstatus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basestaffstatus.entity.BaseStaffStatus;
import org.jeecg.modules.demo.basestaffstatus.service.IBaseStaffStatusService;
import org.jeecg.modules.demo.staffmanagement.entity.StaffManagement;
import org.jeecg.modules.demo.staffmanagement.service.IStaffManagementService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 员工身份表
 * @Author: jeecg-boot
 * @Date: 2022-02-11
 * @Version: V1.0
 */
@Api(tags = "员工身份表")
@RestController
@RequestMapping("/basestaffstatus/baseStaffStatus")
@Slf4j
public class BaseStaffStatusController extends JeecgController<BaseStaffStatus, IBaseStaffStatusService> {
    @Autowired
    private IBaseStaffStatusService baseStaffStatusService;
    @Autowired
    private IStaffManagementService staffManagementService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "员工身份表-分页列表查询")
    @ApiOperation(value = "员工身份表-分页列表查询", notes = "员工身份表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(BaseStaffStatus baseStaffStatus,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<BaseStaffStatus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, baseStaffStatus, req.getParameterMap());
        Page<BaseStaffStatus> page = new Page<>(pageNo, pageSize);
        IPage<BaseStaffStatus> pageList = baseStaffStatusService.page(page, queryWrapper);

        List<BaseStaffStatus> listMap = pageList.getRecords();
        listMap.forEach(bss -> {
            int count = staffManagementService.count(new QueryWrapper<StaffManagement>()
                    .eq("employee_id", bss.getId())
                    .eq("store_id", storeId));
            bss.setStaffNum(count);
            SysRole role = sysRoleService.getById(bss.getRoleId());
            bss.setRoleName(role.getRoleName());
        });
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     */
    @AutoLog(value = "员工身份表-查询全部交易角色")
    @ApiOperation(value = "员工身份表-查询全部交易角色", notes = "员工身份表-查询全部交易角色")
    @GetMapping(value = "/listTradeActor")
    public Result<?> listTradeActor(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<Map> list = baseStaffStatusService.listTradeActor(storeId);


        return Result.OK(list);
    }

    /**
     * 查当前店铺所有的员工身份（用于新建员工时选择员工身份）
     */
    @GetMapping(value = "/getList")
    public Result<?> getListByStoreId(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<BaseStaffStatus> list = baseStaffStatusService.list(new QueryWrapper<BaseStaffStatus>().eq("store_id", storeId));
        if (list == null || list.size() == 0) {
            return Result.error("当前店铺还没未创建员工身份，请到员工身份管理页面创建");
        }
        return Result.OK(list);
    }

    /**
     * 查角色列表（用于新建员工身份时选择角色）
     */
    @GetMapping(value = "/getRoleList")
    public Result<?> getRoleListByStoreId() {
        List<SysRole> list = sysRoleService.list(new QueryWrapper<SysRole>().eq("role_type", "员工"));
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param baseStaffStatus
     * @return
     */
    @AutoLog(value = "员工身份表-添加")
    @ApiOperation(value = "员工身份表-添加", notes = "员工身份表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BaseStaffStatus baseStaffStatus, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        baseStaffStatus.setStoreId(storeId);
        // 当前店铺全部员工身份
        List<BaseStaffStatus> list = baseStaffStatusService.list(new QueryWrapper<BaseStaffStatus>().eq("store_id", storeId));
        // list中与baseStaffStatus同名的员工身份个数
        long count = list.stream().filter(bss -> bss.getStatusName().equals(baseStaffStatus.getStatusName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名员工身份！");
        }
        baseStaffStatus.setServeReward(0.00);
        baseStaffStatus.setProjectReward(0.00);
        baseStaffStatus.setShopReward(0.00);
        baseStaffStatusService.save(baseStaffStatus);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "员工身份表-编辑")
    @ApiOperation(value = "员工身份表-编辑", notes = "员工身份表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BaseStaffStatus baseStaffStatus, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        // 当前店铺全部员工身份
        List<BaseStaffStatus> list = baseStaffStatusService.list(new QueryWrapper<BaseStaffStatus>()
                .eq("store_id", storeId)
                .ne("id", baseStaffStatus.getId()));
        // list中与baseStaffStatus同名的员工身份个数
        long count = list.stream().filter(bss -> bss.getStatusName().equals(baseStaffStatus.getStatusName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名员工身份！");
        }
        baseStaffStatusService.updateById(baseStaffStatus);
        return Result.OK("编辑成功!");
    }

    /**
     * 批量设置提成比例
     */
    @AutoLog(value = "员工身份表-批量设置提成比例")
    @ApiOperation(value = "员工身份表-批量设置提成比例", notes = "员工身份表-批量设置提成比例")
    @PutMapping(value = "/setRewardBatch")
    public Result<?> setRewardBatch(@RequestBody List<BaseStaffStatus> bssList, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        for (BaseStaffStatus bss : bssList) {
            if (bss.getShopReward() < 0 || bss.getShopReward() > 100) {
                return Result.error("提成比例应在0-100范围内，请检查数据");
            }
            baseStaffStatusService.updateById(bss);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "员工身份表-通过id删除")
    @ApiOperation(value = "员工身份表-通过id删除", notes = "员工身份表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        int count = staffManagementService.count(new QueryWrapper<StaffManagement>().eq("employee_id", id));
        if (count > 0) {
            return Result.error("该员工身份下还有关联的员工，请修改员工属性后再删除");
        }
        baseStaffStatusService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "员工身份表-批量删除")
    @ApiOperation(value = "员工身份表-批量删除", notes = "员工身份表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int count = staffManagementService.count(new QueryWrapper<StaffManagement>().in("employee_id", idList));
        if (count > 0) {
            return Result.error("选择的员工身份中还有关联的员工，请修改员工属性后再删除");
        }
        this.baseStaffStatusService.removeByIds(idList);
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "员工身份表-通过id查询")
    @ApiOperation(value = "员工身份表-通过id查询", notes = "员工身份表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BaseStaffStatus baseStaffStatus = baseStaffStatusService.getById(id);
        if (baseStaffStatus == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(baseStaffStatus);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param baseStaffStatus
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaseStaffStatus baseStaffStatus) {
        return super.exportXls(request, baseStaffStatus, BaseStaffStatus.class, "员工身份表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BaseStaffStatus.class);
    }

}
